package com.shujia.spark

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import scala.util.Random

object Demo22PI {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf()

    conf.setAppName("Demo21ClazzNum")

    conf.setMaster("local[4]")

    val sc = new SparkContext(conf)

    /**
      *
      * 计算圆周率
      */


    //构建一个很大的集合
    val list: Range.Inclusive = 0 to 1000000

    //基于集合构建rdd
    val listRDD: RDD[Int] = sc.makeRDD(list, 8)


    //1、随机生成很多点

    val pointRDD: RDD[(Double, Double)] = listRDD.map(i => {

      //随机生成x, y，范围是-1 到 1
      val x: Double = Random.nextDouble() * 2 - 1
      val y: Double = Random.nextDouble() * 2 - 1

      (x, y)
    })

    //计算园内点的数量
    val yuanRDD: RDD[(Double, Double)] = pointRDD.filter {
      case (x: Double, y: Double) =>
        x * x + y * y <= 1
    }

    //计算Pi
    val PI: Double = yuanRDD.count().toDouble / pointRDD.count() * 4


    println(s"PI is $PI")
  }

}
